//
//  textView+Emoticon.swift
//  04CZemoticon
//
//  Created by ksl on 15/12/8.
//  Copyright © 2015年 ksl. All rights reserved.
//

import UIKit

extension UITextView {
    
    ///获取带表情图片的字符串
    func emoticonText() -> String {
        var strM = ""
        //遍历属性文本里面的每一段(迭代)
        //enumerateAttributesInRange: 遍历的范围,遍历整个属性文本
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (result, Range, _) -> Void in
            print("result: \(result),----range: \(Range)")
            print("--------------")
            
            //如果 result 字典中包含""是一个表情
            if let attachment = result["NSAttachment"] as? EmoticonTextAttachment {
                //说明 result字典里有NSAttachment key
                //获取表情名称
                strM += attachment.name!
            } else {
                //普通文本,获取字符串
                let str = (self.attributedText.string as NSString).substringWithRange(Range)
                
                //把截取到的字符串拼接起来
                strM += str
            }
        }
        //返回拼接好的带表情图片名称的字符串
        return strM
    }
    
    /**
     添加一个表情到 textView
     
     - parameter emoticon: 要添加的表情模型
     */
    func insertEmoticon(emoticon: Emoticon) {
        
        //添加 emoji 表情
        if emoticon.emoji != nil {
            //把 emoji 表情添加到 textView 上面
            insertText(emoticon.emoji!)
        }
        
        //添加图片表情
        if emoticon.pngPath != nil {
            //属性文本可以添加图片
            //创建附件
            let attachment = EmoticonTextAttachment()
            
            let width = font!.lineHeight
            
            //设置附件的大小
            attachment.bounds = CGRect(x: 0, y: -4, width: width, height: width)
            
            //给附件添加图片
            attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
            
            //把表情名称赋值给 attachment 附件
            attachment.name = emoticon.chs
            
            //创建一个属性文本,属性文本有一个附件,附件里面有一张图片
            let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            
            //附件没有 font 属性,会变小
            //给附件添加 font 属性
            attrString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
            
            //先把 textView 已有的内容拿出来
            let attrM = NSMutableAttributedString(attributedString: attributedText)
            
            //把图片添加到已有内容里面
            //获取 textView 选中的范围
            attrM.replaceCharactersInRange(self.selectedRange, withAttributedString: attrString)
            
            //重新赋值
            attributedText = attrM
            
            //重新设置选中范围,让光标插入在表情后面
            self.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
        }
    }
}
